<template>
  <div>
    <div class="search">
      <input class="search-input" type="text" placeholder="输入城市名或拼音" v-model="keyword">
    </div>
    <div class="search-content" ref="search" v-show="keyword">
      <ul>
        <li class="search-item border-bottom" v-for="item in list" :key="item.id" @click="handleCityClick(item.name)">{{item.name}}</li>
        <li class="search-item border-bottom nodata" v-show="hasNoData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
  import Bscroll from 'better-scroll'
  import {mapMutations} from 'vuex'

  export default {
    name: "CitySearch",
    props: {
      citys: Object
    },
    data () {
      return {
        keyword: '',
        list: [],
        timer: null
      }
    },
    watch: {
      keyword () {
        if (this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          const reslut = [];
          for (let i in this.citys) {
            this.citys[i].forEach((city) => {
              if (!this.keyword) {
                this.list = [];
                return;
              }
              if ((city.spell.indexOf(this.keyword) > -1) || (city.name.indexOf(this.keyword) > -1)) {
                reslut.push(city);
              }
            });
            this.list = reslut;
          }
        }, 100)
      }
    },
    mounted () {
      this.$nextTick(() => {
        this.scroll = new Bscroll(this.$refs.search, {})
      })
    },
    computed: {
      hasNoData () {
        return !this.list.length;
      }
    },
    methods: {
      handleCityClick (city) {
        this.changeCity(city);
        this.keyword = '';
        this.list = [];
        this.$router.push('/');
      },
      ...mapMutations(['changeCity'])
    }
  }
</script>

<style lang="stylus" scoped>
  @import "~@/assets/styles/varibles.styl";
  .search
    height .72rem
    padding .1rem
    background $bgColor
    .search-input
      width 100%
      height .62rem
      line-height .62rem
      text-align center
      border-radius .06rem
      box-sizing border-box
      padding 0 .1rem
      color #666

  .search-content
    position absolute
    overflow hidden
    top 1.78rem
    left 0
    right 0
    bottom 0
    z-index 1
    background #eee
    .search-item
      line-height .62rem
      padding .2rem
      background #fff
      color #666
      &.nodata
        text-align center
        color #999
</style>
